package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UsuarioDAO;
import model.Usuario;

public class LoginServlet extends HttpServlet {
    
    public LoginServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * Realiza autenticação do usuário ao se logar no sistema
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String msgAutenticacao = null;

        try {
                
            List<Usuario> listaUsuario = UsuarioDAO.getInstance().listar();

            for (int i = 0; i < listaUsuario.size(); i++) {

                if (username.equals(listaUsuario.get(i).getNome()) && password.equals(listaUsuario.get(i).getSenha())) {

                    request.getSession().setAttribute("username", username);
                    RequestDispatcher rd = request.getRequestDispatcher("/pages/empregado/consultar.jsp");
                    rd.forward(request, response);

                }

            }

            msgAutenticacao = "Erro de autenticação";
            
            request.setAttribute("msgAutenticacao", msgAutenticacao);
            response.sendRedirect("login.jsp");

        }
        catch (Exception e) {
                System.err.println(e.getMessage());
        }
        
    }

}